#include <assert.h>
#include <string.h>
#include <WinSock2.h>
#include "Packet.h"

#pragma comment( lib, "ws2_32.lib" )


namespace Message
{

//===========================================================================
static const size_t HEADER_SIZE = sizeof( Header );

//===========================================================================
bool HasNullTerminated(
    char *     str,
    unsigned   size,
    unsigned & len
) {
    assert( str  );
    assert( size );
    
    for( unsigned len = 0; len < size; len++, str++ )
        if( '\0' == *str )
            return true;

    return false;
}
    
//===========================================================================
unsigned Parse(
    void *   ptr,
    unsigned size,
    Packet & packet
) {
    assert( ptr  );
    assert( size );

    if( !( HEADER_SIZE < size ) )
        return 0;

    char *   payload = static_cast< char * >( ptr ) + HEADER_SIZE;
    unsigned len     = 0;
    if( !HasNullTerminated(
            payload,
            size - HEADER_SIZE,
            len
    ) )
        return 0;

    ::memcpy_s( &packet, HEADER_SIZE, ptr, HEADER_SIZE );
    packet.type    = ntohs( packet.type );
    packet.user    = ntohl( packet.user );
    packet.payload = payload;

    return HEADER_SIZE + len + sizeof( '\0' );
}

}; // end of namespace Message